package com.anlogic.sdk.utils;

import java.io.File;
import java.io.FilenameFilter;
import java.net.MalformedURLException;
import java.net.URL;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.browser.IWebBrowser;
import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleManager;
import org.eclipse.ui.console.MessageConsole;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

public class UtilsPlugin extends AbstractUIPlugin {
	public static final String PLUGIN_ID = "com.anlogic.sdk.utils";

	private static UtilsPlugin plugin;

	public void start(BundleContext context) throws Exception {
		super.start(context);
		plugin = this;
	}

	public void stop(BundleContext context) throws Exception {
		plugin = null;
		super.stop(context);
	}

	public static UtilsPlugin getDefault() {
		return plugin;
	}

	public void logMsg(String msg) {
		getLog().log((IStatus) new Status(IStatus.INFO, PLUGIN_ID, IStatus.OK, msg, null));
	}

	public ICommandLauncher getLauncher(MessageConsole stream) {
		return (ICommandLauncher) new Launcher(stream);
	}

	public IProcLauncher getProcLauncher() {
		return (IProcLauncher) new ProcLauncher();
	}

	private MessageConsole getConsole(String name) {
		ConsolePlugin plugin = ConsolePlugin.getDefault();
		IConsoleManager conMan = plugin.getConsoleManager();
		IConsole[] existing = conMan.getConsoles();
		for (int i = 0; i < existing.length; i++) {
			if (name.equals(existing[i].getName()))
				return (MessageConsole) existing[i];
		}
		MessageConsole myConsole = new MessageConsole(name, null);
		conMan.addConsoles(new IConsole[] { (IConsole) myConsole });
		return myConsole;
	}

	private MessageConsole addConsole(String name) {
		ConsolePlugin plugin = ConsolePlugin.getDefault();
		IConsoleManager conMan = plugin.getConsoleManager();
		MessageConsole myConsole = new MessageConsole(name, null);
		conMan.addConsoles(new IConsole[] { (IConsole) myConsole });
		return myConsole;
	}

	public MessageConsole getMessageConsole(String name) {
		MessageConsole console = getConsole(name);
		ConsolePlugin.getDefault().getConsoleManager().showConsoleView((IConsole) console);
		return console;
	}

	public MessageConsole addMessageConsole(String name) {
		MessageConsole console = addConsole(name);
		ConsolePlugin.getDefault().getConsoleManager().showConsoleView((IConsole) console);
		return console;
	}
	
	public void removeMessageConsole(MessageConsole console) {
		ConsolePlugin.getDefault().getConsoleManager().removeConsoles(new IConsole[]{console});
	}

	public static String getFirstFileParallelToWithSuffix(String hwSpecPath, String extension) {
		File hwSpec = new File(hwSpecPath);
		String parent = hwSpec.getParent();
		String hwSpecFolder = (parent == null) ? "." : parent.toString();
		return getFirstFileWithSuffix(hwSpecFolder, extension);
	}

	public static String getFirstFileWithSuffix(String folderPath, String suffix) {
		FilenameFilter filter = new FilterBySuffix(suffix);
		File folder = new File(folderPath);
		if (!folder.exists())
			return null;
		String[] files = folder.list(filter);
		if (files != null && files.length > 0)
			return String.valueOf(folderPath) + File.separator + files[0];
		return null;
	}

	private static class FilterBySuffix implements FilenameFilter {
		private String suffix;

		public FilterBySuffix(String suffix) {
			this.suffix = suffix;
		}

		public boolean accept(File dir, String fileName) {
			return fileName.endsWith(this.suffix);
		}
	}
	
	public static IProject getSelectedProject() {

		IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
		if (window != null) {

			Object selection = window.getSelectionService().getSelection();
			if ((selection != null) && (selection instanceof IStructuredSelection)
					&& (((IStructuredSelection) selection).size() == 1)) {
				Object firstElement = ((IStructuredSelection) selection).getFirstElement();
				if (firstElement instanceof IAdaptable) {
					IProject project = (IProject) ((IAdaptable) firstElement).getAdapter(IProject.class);
					return project;
				}
			}
		}

		return null;
	}
	
	public static void findAndRefreshProject(String filePath) {
		IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
		if (filePath.startsWith(root.getLocation().toString()) || filePath.startsWith(root.getLocation().toOSString())) {
			Path path = new Path(filePath);
			IPath iPath = path.makeRelativeTo(root.getLocation());
			if (iPath.segmentCount() > 0) {
				IProject project = root.getProject(iPath.segment(0));
				if (project.exists()) {
					try {
						project.refreshLocal(2, null);
					} catch (CoreException coreException) {
						
					}
					return;
				}
			}
		}
	}
	
	public static void openBrowser(boolean internal, String href, IWorkbenchWindow window) {
		URL webURL;
		IWorkbenchBrowserSupport browserSupport = window.getWorkbench().getBrowserSupport();
		try {
			webURL = new URL(href);
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
			return;
		} 
		int browserPart = 128;
		if (internal)
			browserPart = 32; 
		try {
			IWebBrowser browser = browserSupport.createBrowser(browserPart, "null", "", "");
			browser.openURL(webURL);
		} catch (PartInitException e1) {
			e1.printStackTrace();
			return;
		} 
	}
}
